package com.harboursoftware.xstorage.operations;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.ListMultimap;
import com.harboursoftware.xstorage.XStorageException;
import com.harboursoftware.xstorage.ac.AccessControlPolicy;
import com.harboursoftware.xstorage.ac.Permission;
import com.harboursoftware.xstorage.fs.BucketNotExistException;
import com.harboursoftware.xstorage.model.XBucket;
import com.harboursoftware.xstorage.model.XElement;
import com.harboursoftware.xstorage.model.XUser;
import com.harboursoftware.xstorage.results.ErrorResult;
import com.harboursoftware.xstorage.results.GetAclResult;
import com.harboursoftware.xstorage.results.Result;

public class GetBucketAcl extends Operation {
    private final static Logger log = LoggerFactory.getLogger(GetBucketAcl.class);
    
    @Override
    public Result execute(XUser requester, XElement element, ListMultimap<String, String> headers,
        Map<String, String> parameters) {
        XBucket bucket = (XBucket)element;
        try {
            fileSystem.loadBucketACP(bucket);
            AccessControlPolicy bucketAcp = bucket.getAcp();
            if(!bucketAcp.checkPermission(requester, getRequiredPermission())) {
                return ErrorResult.create(ErrorResult.Type.ACCESS_DENIED);
            }
            return new GetAclResult(bucket.getAcp());
        } catch (BucketNotExistException e) {
        	ErrorResult errorResult = ErrorResult.create(ErrorResult.Type.NO_SUCH_BUCKET);
        	errorResult.addOtherInfo("BucketName", bucket.getName());
        	return errorResult;
        } catch (XStorageException e) {
            log.error("error occured when get object", e);
            return ErrorResult.create(ErrorResult.Type.INTERNAL_ERROR);
        }
    }

    @Override
    public Permission getRequiredPermission() {
        return Permission.READ_ACP;
    }
}
